import React, { Component } from "react";

// 高阶组件
const withMouse = (BaseComponent) => {
    // 该类组件用来提供状态逻辑
    return class Wrapper extends React.Component {
        state = {
            x: 0,
            y: 0,
        };

        handleMousemove = (e) => {
            const { pageX, pageY } = e;

            this.setState({
                x: pageX,
                y: pageY,
            });
        };

        componentDidMount() {
            window.addEventListener("mousemove", this.handleMousemove);
        }

        componentWillUnmount() {
            window.removeEventListener("mousemove", this.handleMousemove);
        }

        render() {
            const { x, y } = this.state;
            return <BaseComponent x={x} y={y} />;
        }
    };
};

const Position = ({ x, y }) => {
    return (
        <div>
            鼠标当前位置：(x: {x}, y: {y})
        </div>
    );
};
class PositionClass extends React.Component {
    render() {
        return (
            <div>
                获取当前位置
                <p>x: {this.props.x}</p>
                <p>y: {this.props.y}</p>
            </div>
        );
    }
}
const PositionWithMouse = withMouse(PositionClass);
export default PositionWithMouse; // 包装后的组件
